import { useEffect, useState } from "react";
import useSetState from "@/hooks/useSetState";

type useGetFakeCaptchaProps = {
	manual?: boolean;
	onSuccess?: (src: any) => void;
};

const getFakeCaptcha = async () => {};

const useGetFakeCaptcha = (options: useGetFakeCaptchaProps) => {
	const [src, setSrc] = useSetState();
	const [captchaToken, setCaptchaToken] = useState<string>();
	const { manual, onSuccess } = options;

	const run = () => {
		return getFakeCaptcha()
			.then(res => {
				if (!res) return;
				// 图片地址
				const imgUrl = URL.createObjectURL(res.data);

				// 图片token
				const captchaTokens = res?.headers.get("captcha-token");

				setSrc(imgUrl, () => onSuccess?.(imgUrl));
				setCaptchaToken(captchaTokens);
			})
			.catch(e => {
				setSrc("");
				setCaptchaToken("");
				console.error(e);
			});
	};

	useEffect(() => {
		if (!manual) {
			run().then();
		}
	}, []);

	return {
		src,
		captchaToken,
		run
	};
};
export default useGetFakeCaptcha;
